package com.luo.bbs.ums.webapi.controller;

import com.luo.common.restful.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
@Slf4j
public class UploadController {
    @Value("${bbs-ums.resource.path}")
    private File resourcePath;
    @Value("${bbs-ums.resource.host}")
    private String resourceHost;

    @PostMapping("/picture")
    public JsonResult uploadPicture(@RequestParam("file") MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String ext = filename.substring(filename.lastIndexOf("."));
        String name = UUID.randomUUID() + ext;//图片名

        String avatar = "tou-xiang";

        File folder = new File(resourcePath,avatar);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        File imgFile = new File(folder,name);
        file.transferTo(imgFile);

        String url = resourceHost + "/" + avatar + "/" + name;
        log.debug(imgFile.getAbsolutePath()+"绝对路径");
        log.debug(url);
        return JsonResult.ok(url);
    }

}
